<style>
.upload-img {
  width: 100%;
  height: 200px;
}

.demo-upload-list {
  display: inline-block;
  width: 100%;
  height: 160px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
  margin-right: 4px;
}

.demo-upload-list img {
  width: 100%;
  height: 100%;
}

.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, .6);
}

.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}

.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>

<template>
  <Row class="layout-content-body">
    <dtable :columns="columns" :dataAll="dataAll" :dataShow="dataShow" :totals="total" 
    add delCheck check op @delCheck="delCheck" 
    @sortOrder="sortOrder" @add="add" @edit="edit" @refresh="refresh()" @changePage="changePage" @search="getall" @changeSize="changeSize" :loading="loading"></dtable>
    <Modal title="视频信息" v-model="editData" width="600" :mask-closable="false" class="editm" @on-ok="asyncOK" @on-cancel="asyncCancel">
      <Form ref="editForm" :model="formItem" :label-width="80" :rules="ruleValidate">
        <Form-item label="视频标题" prop="Title">
          <Input v-model="formItem.Title" placeholder="请输入" @on-enter="asyncOK()"></Input>
        </Form-item>
        <Form-item label="资源上传">
          <Row>
            <i-col span="12">
              <Upload v-if="!addid" ref="upload" :on-success="handleSuccess" :format="['mp4','flv']" :max-size="204800" :on-format-error="handleFormatError" :on-exceeded-size="handleMaxSize" :on-remove="handleRemove" :before-upload="handleBeforeUpload" type="drag" :action="actionUrl">
                <div style="padding: 20px 0">
                  <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                  <p>点击或将文件拖拽到这里上传（仅限于mp4、flv格式文件）</p>
                </div>
              </Upload>
            </i-col>
            <i-col span="12">
              <div class="demo-upload-list">
                <img :src="imgSrc(formItem.Img)" class="upload-img">
              </div>
            </i-col>
          </Row>
        </Form-item>
        <Form-item label="状态" prop="Status">
          <Radio-group v-model.number="formItem.Status">
            <Radio label="1">启用</Radio>
            <Radio label="0">停用</Radio>
          </Radio-group>
        </Form-item>
        <Form-item label="发布范围" prop="Scope">
          <Radio-group v-model.number="formItem.Scope">
            <Radio label="2" v-if="getScope">全系统</Radio>
            <Radio label="1">全单位</Radio>
            <Radio label="0">本部门</Radio>
            <Radio label="3">指定用户</Radio>
          </Radio-group>
        </Form-item>
        <Form-item v-if="formItem.Scope==='3' || formItem.Scope===3">
          <Transfer :titles="['未授权', '已授权']" :data="TransData" :target-keys="targetKeys" :render-format="render" @on-change="handleChange"></Transfer>
        </Form-item>
        <Form-item label="说明" prop="Remark">
          <Input v-model="formItem.Remark" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入...">
          </Input>
        </Form-item>
      </Form>
    </Modal>
  </Row>
</template>

<script>
// import api from '@/api'
import {
  timeFormat
} from '@/common/filter'
import {
  SERVER_CPT_URL,
  V_ROOT
} from '@/api/config'
import {
  mapMutations,
  mapGetters,
  mapState
} from 'vuex'
import dtable from '@/components/table/btable.vue' //采用biztable
import moment from "moment"
export default {
  data() {
    return {
      loading: false, //点击确定按钮时，确定按钮是否显示 loading 状态，开启则需手动设置visible来关闭对话框
      columns: [

        {
          title: '名称',
          key: 'Title',
          sortable: true
        },
        {
          title: '大小(KB)',
          key: 'Size',
          sortable: true
        },
        {
          title: '时长',
          key: 'Longtime',
          sortable: true
        },
        {
          title: '所属单位',
          key: 'OrgName',
          sortable: true
        },
        {
          title: '类型',
          key: 'Type',
          sortable: true,
          render(row, column, index) {
            return `${(row.Type === 0) ? '人工上传' : '直播录制'}`;
          }
        },
        {
          title: '范围',
          key: 'Sname',
          sortable: true,
        },

        {
          title: '提供者',
          key: 'Updater',
          sortable: true
        },
        {
          title: '提供时间',
          key: 'Utime',
          sortable: true,
          render: (h, params) => {
            return h('div', [
              h('strong', timeFormat(params.row.Utime))
            ]);
          }
        },
        {
          title: '状态',
          key: 'status',
          width: 80,
          sortable: true,
          render(row, column, index) {
            return `${(row.status === 0) ? '失效' : '有效'}`;
          }
        },
      ], //表格样式
      dataAll: [], //表格数据来源
      dataShow: true, //是否显示表格数据查看表单
      editData: false, //显示编辑表单
      formItem: {
        Id: '',
        Title: '',
        Scope: 0,
        Type: 0,
        Size: 0,
        Length: 0,
        Longtime:'',
        Img: "",
        Url: '',
        OrgName: '',
        Status: 1,
        Remark: ''
      }, //数据编辑表单
      ruleValidate: {
        Title: [{
          required: true,
          message: '标题不能为空',
          trigger: 'blur'
        }],
        Url: [{
          required: true,
          message: '视频地址不能为空',
          trigger: 'blur'
        }],
        Img: [{
          required: true,
          message: '图片地址不能为空',
          trigger: 'blur'
        }],

      }, //数据编辑表单验证规则
      addid: true, //true为修改模式，false为添加模式
      org: [],
      total: 0,
      imgName: 'http://192.168.1.139/live/time.jpg',
      visible: false,
      TransData: [],
      targetKeys: [],
      isUpload: false,
      pagedata: {
        pagesize: 10,
        page: 1,
        searchKey: '',
        sortby: ['Ctime'],
        order: ['desc']
      }
    }
  },
  components: {
    dtable,
  },
  computed: {
    state() {
      return this.$store.state.app
    },
    actionUrl() {
      return SERVER_CPT_URL + '/upload/VideoUpload?token=' + this.state.token
    },
    getScope() {
      if (this.state.role.Type > 0) {
        return false
      } else {
        return true
      }
    },
  },
  watch: {},
  methods: {
    refresh() {
      this.getall(this.pagedata)
    },
    //      排序
    sortOrder(current) {
      console.log(current)
      this.pagedata = current
      this.getall(this.pagedata)
    },
    imgSrc(data) {
      if(!data){
        return "/static/img/time.jpg"
      }
      return  V_ROOT + "/"  + data
    },
    //富文本框内容对应
    updateData(data) {
      // sync content to component
      this.formItem.Content = data
    },
    //     获取资源名称
    getNameById(value) {
      let rname = ""
      if (value || '') {
        let rv = this.dataAll.filter((col, index) => col.Id === value)
        rname = rv[0].Name
      }
      return rname
    },
    //      改变页码大小
    changeSize(current) {
      this.pagedata.page = current
      this.getall(this.pagedata)
    },
    //      改变页码
    changePage(current) {
      console.log(current)
      this.pagedata = current
      this.getall(this.pagedata)
    },
    getall(pg) {
      this.loading = true
      this.$api.getVideo(pg).then(res => {
        if (!res.error) {
          this.total = res.Data.total
          this.dataAll = res.Data.tabledata
        } else {
          this.$Message.error(res.message)
        }
        this.loading = false;
      })
    },
    getUser() {
      this.$api.GetAllOrgUsers().then(res => {
        console.log(res.Data)
        if (!res.error) {
          this.TransData = res.Data
        } else {
          this.$Message.error(res.message)
        }
      }, err => {
        this.$Message.error(res.message, 4)
      })
    },
    getVideoUser(index) {
      this.$api.GetVideoUserByVideo(index).then(res => {
        console.log(res.Data)
        if (!res.error && res.Data) {
          this.targetKeys = res.Data
        } else {
          this.targetKeys = []
        }
      })
    },

    edit(index) {
      this.getVideoUser(index.Id)
      this.addid = true
      this.formItem = index
      this.editData = true
    },
    add() {
      this.addid = false
      this.$refs['editForm'].resetFields()
      //        this.formItem.Rtime=this.getRtime
      this.editData = true
      this.VideoCancel()
    },
    asyncOK() {
      this.formItem.users = this.targetKeys
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          if (this.addid) {
            this.$api.updateVideo(this.formItem).then(res => {
              if (!res.error) {
                this.getall(this.pagedata)
                this.$Message.success(res.message)
              } else {
                this.$Message.error(res.message, 4)
              }
            }, err => {
              this.$Message.error(res.message, 4)
            })
          } else if (!this.addid) {
            this.$api.addVideo(this.formItem).then(res => {
              if (!res.error) {
                this.getall(this.pagedata)
                this.$Message.success(res.message)
              } else {
                this.$Message.error(res.message, 4)
              }
            }, err => {
              this.$Message.error(res.message, 4)
            })
            this.$refs['upload'].clearFiles()
            this.$refs['editForm'].resetFields()
          }
          setTimeout(() => {
            this.editData = false;
          }, 1000);
        } else {
          this.$Message.error('表单验证失败!');
        }
      })
      this.editData = false
      this.isUpload = false
    },
    asyncCancel() {
      this.VideoCancel()
      this.getall(this.pagedata)
    },
    del(row) {
      this.$api.deleteVideo(row).then(res => {
        if (!res.error) {
          this.getall(this.pagedata)
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      }, err => {
        this.$Message.error(res.message, 4)
      })
    },
    VideoCancel() {
      let row = {
        Url: this.formItem.Url
      }
      if (this.isUpload) {
        this.$api.VideoCancel(row).then(res => {
          console.log("ok")
        })
        this.$refs['upload'].clearFiles()
      }
      this.formItem.Img = '/imgs/time.jpg'
      this.$refs['editForm'].resetFields()
      if (!this.formItem.url) {
        return
      }

      this.isUpload = false
    },
    delCheck(row) {
      this.$api.deleteVideos(row).then(res => {
        if (!res.error) {
          this.getall(this.pagedata)
          this.$Message.success(res.message)
        } else {
          this.$Message.error(res.message, 4)
        }
      }, err => {
        this.$Message.error(res.message, 4)
      })
    },
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      // 从 upload 实例删除数据
      this.VideoCancel()
      //        const fileList = this.$refs.upload.fileList;
      //        this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleSuccess(res, file) {
      // 因为上传过程为实例，这里模拟添加 url
      //        this.$Notice.warning({
      //          title: '超出文件大小限制',
      //          desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
      //        });
      console.log(res, file)
      this.imgName = res.jdata.Img
      this.formItem = res.jdata
      //        this.formItem.Title = res.jdata.Title
      //        this.formItem.Img = this.imgName
      //        this.formItem.Url = res.jdata.Url
      this.isUpload = true
      //        file.url = 'https://o5wwk8baw.qnssl.com/7eb99afb9d5f317c912f08b5212fd69a/avatar';
      //        file.name = '7eb99afb9d5f317c912f08b5212fd69a';
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: '文件格式不正确',
        desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: '超出文件大小限制',
        desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
      });
    },
    handleBeforeUpload() {
      const check = this.$refs.upload.fileList < 2;
      //        console.log(check)
      if (!check) {
        this.$Notice.warning({
          title: '不能同时上传多个视频'
        });
      }
      return check;
    },
    render(item) {
      return item.label;
    },
    handleChange(newTargetKeys, direction, moveKeys) {
      console.log(newTargetKeys);
      console.log(direction);
      console.log(moveKeys);
      this.targetKeys = newTargetKeys;
    }

  },
  mounted() {
    this.getall(this.pagedata)
    this.getUser()
  }
}
</script>
